package com.das.metrocloud.ssoserver.resource;

import com.das.framework.web.rs.service.*;
import org.springframework.stereotype.*;
import org.springframework.web.client.*;
import com.das.metrocloud.ssoserver.config.*;
import com.das.cloud.system.service.*;
import com.das.metrocloud.ssoserver.service.*;
import org.springframework.beans.factory.annotation.*;
import com.das.cloud.system.entity.*;
import javax.ws.rs.core.*;
import javax.servlet.http.*;
import com.das.framework.common.utils.*;
import org.apache.commons.codec.digest.*;
import com.das.framework.web.spring.utils.*;
import com.das.framework.common.redis.utils.*;
import org.apache.commons.lang3.*;
import com.das.framework.common.annotation.*;
import com.das.framework.common.webmsg.*;
import org.springframework.http.*;
import org.springframework.util.*;
import com.das.framework.common.extvo.*;
import java.util.*;
import com.das.framework.common.exception.*;
import javax.ws.rs.*;

@Component
@Path("/auth/security")
@Produces({ "application/json;charset=UTF-8" })
public class UserLoginResource extends SupportResource
{
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private GlobalVariable globalVariable;
    @Autowired
    private JwtTokenSevice jwtTokenUtil;
    @Autowired
    private SysAccountService accountService;
    @Autowired
    private UserResourcesService userResourcesService;
    @Value("${dascloud.token.expire:1800000}")
    private long expire;
    @Value("${dascloud.token.refresh: 300000}")
    private long refresh;
    @Value("${dascloud.token.client-count: 1}")
    private Integer clientCount;
    @Value("${dascloud.bizsys.msg:''}")
    private String msgServerUrl;
    
    @POST
    @Path("/login")
    @IgnoreUserToken
    public ResultVO login(final SysAccountEntity entity, @Context final HttpServletRequest request, @Context final HttpServletResponse response) throws Exception {
        final ResultVO result = new ResultVO();
        if (Tools.StringIsNullOrSpace(entity.getAccount()) || Tools.StringIsNullOrSpace(entity.getPassword())) {
            result.setSuccess(false);
            result.setMessage("\u8bf7\u6c42\u53c2\u6570\u4e0d\u5b8c\u6574");
            return result;
        }
        final SysAccountEntity accountEntity = this.accountService.findByAccount(entity.getAccount());
        if (accountEntity == null) {
            result.setSuccess(false);
            result.setMessage("\u7528\u6237\u4e0d\u5b58\u5728\u6216\u5df2\u88ab\u5220\u9664.");
            UserLoginResource.log.info("\u7528\u6237" + entity.getAccount() + "\u767b\u5f55\u5931\u8d25\uff1a" + result.getMessage());
            return result;
        }
        final String dbpwd = DigestUtils.md5Hex(entity.getPassword().trim());
        if (!dbpwd.equals(accountEntity.getPassword())) {
            result.setSuccess(false);
            result.setMessage("\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef.");
            UserLoginResource.log.info("\u7528\u6237" + entity.getAccount() + "\u767b\u5f55\u5931\u8d25\uff1a" + result.getMessage());
            return result;
        }
        if (!"1".equals(accountEntity.getStatus())) {
            result.setSuccess(false);
            result.setMessage("\u7528\u6237\u8d26\u53f7\u5df2\u88ab\u6ce8\u9500\u6216\u7981\u7528\uff0c\u8bf7\u8054\u7cfb\u7ba1\u7406\u5458.");
            UserLoginResource.log.info("\u7528\u6237" + entity.getAccount() + "\u767b\u5f55\u5931\u8d25\uff1a" + result.getMessage());
            return result;
        }
        final String loginIp = WebTools.getRequestIp(request);
        final String userAgent = request.getHeader("User-Agent");
        final String prefixTokenId = RedisCacheKeyUtils.tokenKey((String)accountEntity.getId());
        final String tokenId = prefixTokenId + "_" + RandomStringUtils.randomAlphanumeric(10).toUpperCase();
        final TokenVo token = new TokenVo((String)accountEntity.getId(), loginIp, System.currentTimeMillis());
        token.setAccount(accountEntity.getAccount());
        token.setName(accountEntity.getName());
        token.setStationNo(this.globalVariable.getCurrentStationNo());
        token.setStationName(this.globalVariable.getCurrentStationName());
        token.setLoginTime(System.currentTimeMillis());
        token.setUserAgent(userAgent);
        final LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId((String)accountEntity.getId());
        loginInfo.setAccount(accountEntity.getAccount());
        loginInfo.setName(accountEntity.getName());
        loginInfo.setLoginIp(loginIp);
        loginInfo.setUserType("CZY");
        loginInfo.setStationNo(this.globalVariable.getCurrentStationNo());
        loginInfo.setStationName(this.globalVariable.getCurrentStationName());
        final String jwtToken = this.jwtTokenUtil.generateToken(loginInfo);
        token.setJwt(jwtToken);
        this.redisUtils.set(tokenId, (Object)token, Long.valueOf(this.expire));
        this.userResourcesService.saveUserPermissionToRedis((String)accountEntity.getId());
        result.put((Object)"token", (Object)tokenId);
        result.put((Object)"jwtToken", (Object)jwtToken);
        result.put((Object)"userInfo", (Object)loginInfo);
        this.clientLoginCountCheck(loginIp, prefixTokenId, tokenId, jwtToken);
        UserLoginResource.log.info("\u7528\u6237:" + accountEntity.getAccount() + "\u767b\u5f55\u6210\u529f,Token:" + tokenId + ", ip:" + loginIp + ", userAgent:" + userAgent);
        return result;
    }
    
    private void clientLoginCountCheck(final String loginIp, final String prefixTokenId, final String tokenId, final String jwtToken) {
        if (this.clientCount > 1) {
            return;
        }
        final LinkedHashSet<String> arr = (LinkedHashSet<String>)this.redisUtils.gets(prefixTokenId + "*");
        if (arr != null && arr.size() > 1) {
            arr.remove(tokenId);
            for (final String key : arr) {
                final TokenVo tokenVo = (TokenVo)this.redisUtils.get(key);
                if (tokenVo != null) {
                    tokenVo.setStatus(2);
                }
                this.redisUtils.set(key, (Object)tokenVo, Long.valueOf(300L));
            }
        }
    }
    
    private void sendOffLineMsg(final String loginIp, final String jwtToken, final String key) {
        try {
            final HttpHeaders headers = new HttpHeaders();
            headers.add("JwtToken", jwtToken);
            final WebMessage message = new WebMessage();
            message.setBid(key);
            message.setTitle("\u4e0b\u7ebf\u901a\u77e5");
            message.setType("03");
            message.setContents("\u60a8\u7684\u8d26\u53f7\u5728" + loginIp + "\u767b\u5f55\uff0c\u60a8\u5df2\u88ab\u8feb\u4e0b\u7ebf\uff0c\u5982\u975e\u672c\u4eba\u64cd\u4f5c\u8bf7\u53ca\u65f6\u8054\u7cfb\u7ba1\u7406\u5458!");
            final HttpEntity<WebMessage> httpEntity = (HttpEntity<WebMessage>)new HttpEntity((Object)message, (MultiValueMap)headers);
            final String url = this.msgServerUrl + "/webMessage/sendClient/" + key;
            final ResultVO resultVO = (ResultVO)this.restTemplate.postForObject(url, (Object)httpEntity, (Class)ResultVO.class, new Object[0]);
            if (resultVO == null) {
                UserLoginResource.log.warn("\u7528\u6237" + key + "\u88ab\u8feb\u4e0b\u7ebf\u901a\u77e5\u53d1\u9001\u5931\u8d25\uff1a\u670d\u52a1\u672a\u54cd\u5e94" + url);
                return;
            }
            UserLoginResource.log.warn("\u7528\u6237" + key + "\u88ab\u8feb\u4e0b\u7ebf\u901a\u77e5\u53d1\u9001" + (resultVO.isSuccess() ? "\u6210\u529f" : ("\u5931\u8d25\uff1a" + resultVO.getMessage())));
        }
        catch (Exception e) {
            UserLoginResource.log.info("\u7528\u6237" + key + "\u88ab\u8feb\u4e0b\u7ebf\u901a\u77e5\u53d1\u9001\u9519\u8bef\uff1a" + e.getMessage(), (Throwable)e);
        }
    }
    
    private void cacheUserMenu(final String userId) {
        final List<MenuVo> listMenu = new ArrayList<MenuVo>();
        MenuVo m = new MenuVo();
        m.setName("\u7cfb\u7edf\u7ba1\u7406");
        listMenu.add(m);
        m = new MenuVo();
        m.setName("\u6743\u9650\u7ba1\u7406");
        listMenu.add(m);
        this.redisUtils.lSet(RedisCacheKeyUtils.userMenuKey(userId), (Object)listMenu);
    }
    
    @GET
    @Path("/logout")
    public ResultVO logout() throws NotAuthorizationException {
        final ResultVO result = new ResultVO();
        final String authorization = super.getAuthorizationValue();
        if (Tools.StringIsNullOrSpace(authorization)) {
            result.setSuccess(false);
            result.setMessage("\u672a\u627e\u5230\u8bf7\u6c42\u7684\u8ba4\u8bc1\u4fe1\u606f.");
            return result;
        }
        final String permissId = RedisCacheKeyUtils.userPermissionKey(authorization.replace("TK_", ""));
        final String userMenuId = RedisCacheKeyUtils.userMenuKey(authorization.replace("TK_", ""));
        this.redisUtils.remove(authorization);
        this.redisUtils.remove(permissId);
        this.redisUtils.remove(userMenuId);
        result.setSuccess(true);
        result.setMessage("\u6ce8\u9500\u6210\u529f");
        return result;
    }
}
